﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Reflection;
using System.IO;

/// <summary>
/// Summary description for TemplateHelper
/// </summary>
/// <summary>
/// A Template Helper class that uses ASP.NET User Controls for its various operations
/// Author: S.M. Raihan Iqbal
/// </summary>

public class TemplateHelper
{
    public TemplateHelper() { }

    public TemplateHelper(UserControl template)
    {
        _template = template;
    }


    public UserControl Template
    {
        get
        {
            return _template;
        }
        set
        {
            _template = value;
        }
    }

    private UserControl _template;

    /// <summary>
    /// Sets the value of a public property in the template
    /// </summary>
    /// <param name="Id">The name of the property</param>
    /// <param name="value">The target value</param>
    public void SetValue(string Id, object value)
    {
        if (_template != null)
        {
            Type type = _template.GetType();
            PropertyInfo propertyInfo = type.GetProperty(Id);
            if (propertyInfo == null)
                throw new ArgumentException(Id + " not found.");
            propertyInfo.SetValue(_template, value, null);
        }
        else
            throw new NullReferenceException("Property Template cannot be null");
    }

    /// <summary>
    /// Returns the rendered HTML of the current template
    /// </summary>
    /// <returns>string</returns>
    public string GetTemplateContent()
    {
        StringBuilder htmlResponse = new StringBuilder();
        using (StringWriter sw = new StringWriter(htmlResponse))
        {
            using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
            {
                _template.RenderControl(textWriter);
            }
        }
        return htmlResponse.ToString();
    }

    /// <summary>
    /// Loads a User Control from the provided path
    /// </summary>
    /// <param name="pathToControl">The relative path to the user control</param>
    /// <returns></returns>
    public static UserControl LoadUserControl(string pathToControl)
    {
        Page p = new Page();
        UserControl uc = new UserControl();
        uc = (UserControl)p.LoadControl(pathToControl);
        uc.DataBind();
        return uc;
    }
}